package com.edu.tankgame;
import java.io.*;
import java.util.Vector;

/**
 * 该类记录相关的信息 和文件交互
 */
public class Recorder {
    //定义变量，记录我方击毁的敌人坦克数量
    private static int allEnemyTankNum = 0;
    //定义IO对象

    private static BufferedWriter bw = null;
    private static BufferedReader br = null;
    //定义一个Node的Vector的对象
    public static  Vector<Node> nodes = new Vector<>();
    private static String recordFile = "D:\\java_code\\tankGame04\\src\\myRecord.txt";
    //定义一个Vector 指向MyPanel 中的Vector
    private static Vector<EnemyTank> enemyTanks = null;

    public static void setEnemyTanks(Vector<EnemyTank> enemyTanks) {
        Recorder.enemyTanks = enemyTanks;
    }
//返回一个记录文件的路径
    public static String getRecordFile() {
        return recordFile;
    }

    //增加一个方法，用于读取recordFile坦克信息
    public static Vector<Node> getNodesAllEnemyTankRec() {
        try {
            br = new BufferedReader(new FileReader(recordFile));
            allEnemyTankNum = Integer.parseInt(br.readLine());
            //循环文件，生成Node
            String line = " ";
            while ((line = br.readLine()) != null) {
                String[] xyd = line.split(" ");
                Node node = new Node(Integer.parseInt(xyd[0]), Integer.parseInt(xyd[1]), Integer.parseInt(xyd[2]));
                nodes.add(node);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            try {
                if(br != null){
                    br.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return nodes;
    }
    //增加一个方法，当游戏退出时我们将allEnemyTankNum 保存到 recordFile
    //对keepRecord方法进行升级，保存敌人坦克的坐标和方向
    public static void keepRecord() {
        try {
             bw = new BufferedWriter(new FileWriter(recordFile));
             bw.write(allEnemyTankNum +"\r\n");
            for (int i = 0; i < enemyTanks.size(); i++) {
                EnemyTank enemyTank = enemyTanks.get(i);
                if(enemyTank.isLive){
                    //保存enemyTank信息
                    String record = enemyTank.getX() + " " + enemyTank.getY()+ " " + enemyTank.getDirect() ;
                    //写入到文件
                    bw.write(record + "\r\n");

                }
            }
             //遍历保存敌人坦克的Vector，根据情况保存
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if(bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static int getAllEnemyTankNum() {
        return allEnemyTankNum;
    }

    public static void setAllEnemyTankNum(int allEnemyTankNum) {
        Recorder.allEnemyTankNum = allEnemyTankNum;
    }
    //当我方坦克击毁一个敌人坦克就  allEnemyTankNum++
    public static void allAllEnemyTankNum() {
        Recorder.allEnemyTankNum++;
    }
}
